package io.hepu.robotize.page;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class PageRequest implements Serializable {
    private static final int MAX_PAGE_SIZE = 100;

    private static final int DEFAULT_PAGE = 1;
    private static final int DEFAULT_SIZE = 10;

    private int page = DEFAULT_PAGE;
    private int size = DEFAULT_SIZE;
    private final Map<String, Object> conditions = new HashMap<>();
    private final Map<String, String> orders = new HashMap<>();

    public PageRequest() {
    }

    public PageRequest(int page, int size) {
        this.page = Math.max(DEFAULT_PAGE, page);
        this.size = Math.max(DEFAULT_SIZE, Math.min(size, MAX_PAGE_SIZE));
    }

    public int getOffset() {
        return (page - 1) * size;
    }

    public int getPage() {
        return page;
    }

    public int getSize() {
        return size;
    }

    public Map<String, String> getOrders() {
        return orders;
    }

    public Map<String, Object> getConditions() {
        return conditions;
    }

    public void setOrders(Map<String, String> orders) {
        this.orders.putAll(orders);
    }

    public void setConditions(Map<String, Object> conditions) {
        this.conditions.putAll(conditions);
    }

    // 添加查询条件
    public void addWhere(String key, Object value) {
        conditions.put(key, value);
    }

    // 添加排序字段及方向
    public void addOrderBy(String field, String direction) {
        orders.put(field, "DESC".equalsIgnoreCase(direction) ? direction : "ASC");
    }

    @Override
    public int hashCode() {
        return Objects.hash(page, size, conditions, orders);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof PageRequest)) {
            return false;
        }
        PageRequest that = (PageRequest) obj;
        return page == that.page && size == that.size &&
                Objects.equals(conditions, that.conditions) && Objects.equals(orders, that.orders);
    }

    @Override
    public String toString() {
        return "PageRequest{" +
                "page=" + page +
                ", size=" + size +
                ", conditions=" + conditions +
                ", orders=" + orders +
                '}';
    }
}
